package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.medical.dao.local.SangerHscheqMapper;
import com.zhijian.medical.entity.dto.SangerCxPcrCwchSjDto;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Sanger;
import com.zhijian.medical.entity.po.SangerHscheq;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.SangerHscheqSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.SangerHscheqSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.SangerHscheqVo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.SangerStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.ExperimentProcessSampleLogService;
import com.zhijian.medical.service.ExperimentProcessSampleService;
import com.zhijian.medical.service.SangerHscheqService;
import com.zhijian.medical.service.SangerService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 一代测序-核酸纯化二区 （测序PCR产物纯化）、核酸扩增二区（变性）业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-16 15:45:21
 */
@Slf4j
@Service
public class SangerHscheqServiceImpl implements SangerHscheqService {

    @Autowired
    private SangerHscheqMapper mapper;

    @Autowired
    private SangerService sangerService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public SangerHscheq selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public SangerHscheq selectBySangerId(Long sangerId) {
        return mapper.selectBySangerId(sangerId);
    }

    @Override
    public SangerHscheqVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public SangerHscheqVo selectVoBySangerId(Long sangerId) {
        SangerHscheqVo sangerHscheqVo = mapper.selectVoBySangerId(sangerId);
        if (Objects.isNull(sangerHscheqVo)) {
            return null;
        }
        Sanger sanger = sangerService.selectById(sangerId);
        if (Objects.isNull(sanger)) {
            return null;
        }
        sangerHscheqVo.setResult(sanger.getStatus() > SangerStatusEnum.HSCHEQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        sangerHscheqVo.setResultStr(sanger.getStatus() > SangerStatusEnum.HSCHEQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String cxpcrcwchsjData = sangerHscheqVo.getCxpcrcwchsjData();
        if (StringUtils.isNotBlank(cxpcrcwchsjData)) {
            sangerHscheqVo.setCxpcrcwchsjDataList(JsonUtil.toArray(cxpcrcwchsjData, SangerCxPcrCwchSjDto.class));
        }
        return sangerHscheqVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(SangerHscheq sangerHscheq) {
        Date now = new Date();
        sangerHscheq.setCreateTime(now);
        sangerHscheq.setUpdateTime(now);
        sangerHscheq.setSytmqj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHscheq.setAzfzzsop010dcxpcrcwjxchjbxcl(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHscheq.setAzfzzsop010jxbc(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHscheq.setGcywyc(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHscheq.setLxj(StatusEnum.NORMAL.getCode().byteValue());
        sangerHscheq.setAqg(StatusEnum.NORMAL.getCode().byteValue());
        sangerHscheq.setPcry(StatusEnum.NORMAL.getCode().byteValue());
        sangerHscheq.setQjjzwzssygztm(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHscheq.setQjyyq(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHscheq.setQjlxj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHscheq.setClsyfqw(StatusEnum.UN_NORMAL.getCode().byteValue());
        return mapper.insert(sangerHscheq) > 0 ? sangerHscheq.getId() : 0L;
    }

    @Override
    public boolean update(SangerHscheq sangerHscheq) {
        Date now = new Date();
        sangerHscheq.setUpdateTime(now);
        return mapper.updateByPrimaryKey(sangerHscheq) != 0;
    }

    @Override
    public Integer count(SangerHscheqSearchVo sangerHscheqSearchVo) {
        return mapper.count(sangerHscheqSearchVo);
    }

    @Override
    public List<SangerHscheqVo> selectList(SangerHscheqSearchVo sangerHscheqSearchVo) {
        return mapper.selectList(sangerHscheqSearchVo);
    }

    @Override
    public Page<SangerHscheqVo> selectPage(SangerHscheqSearchVo sangerHscheqSearchVo) {
        //先直接查总数
        int count = count(sangerHscheqSearchVo);
        //分页
        Page<SangerHscheqVo> page = new Page<>(true, count, sangerHscheqSearchVo.getPageNum(), sangerHscheqSearchVo.getPageSize());
        sangerHscheqSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<SangerHscheqVo> responseVos = this.selectList(sangerHscheqSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(SangerHscheqSaveOrUpdateVo sangerHscheqSaveOrUpdateVo) {
        Long sangerId = sangerHscheqSaveOrUpdateVo.getSangerId();
        Sanger sanger = sangerService.selectById(sangerId);
        AssertUtil.notNull(sanger, "此实验不存在或者已被删除");
        if (sanger.getStatus() < SangerStatusEnum.CXQ.getCode().byteValue()) {
            //将实验的状态修改
            sangerService.updateByPrimaryKeySelective(Sanger.builder()
                    .id(sangerId)
                    .status(SangerStatusEnum.CXQ.getCode().byteValue())
                    .build());
        }
        List<SangerCxPcrCwchSjDto> cxpcrcwchsjDataList = sangerHscheqSaveOrUpdateVo.getCxpcrcwchsjDataList();
        if (CollectionUtil.isNotEmpty(cxpcrcwchsjDataList)) {
            sangerHscheqSaveOrUpdateVo.setCxpcrcwchsjData(JsonUtil.toString(cxpcrcwchsjDataList));
        }
        SangerHscheq oldSangerHscheq = this.selectBySangerId(sangerId);
        SangerHscheq dbParam = new SangerHscheq();
        BeanUtils.copyProperties(sangerHscheqSaveOrUpdateVo, dbParam);
        if (Objects.isNull(oldSangerHscheq)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(oldSangerHscheq.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .experimentProcessId(sangerId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(sangerId)
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .op(String.format("%s%s-%s", sanger.getName(), sanger.getProcessNumber(), SangerStatusEnum.HSCHEQ.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

}